package com.example.seh.util;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.example.seh.R;
import com.example.seh.UserDTO;
import com.example.seh.constant.Constant;
import com.example.seh.home.substitution.AddressInfoDTO;
import com.example.seh.person.ListenerManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private ImageView avatar;
    private RelativeLayout passwordLogin, codeLogin;
    private EditText phone, password, code;
    private Button loginBtn;
    private TextView regist, exchange, forgetPassword, getCodeBtn;
    private boolean isPassword = true;
    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    getAddress();
                    break;
                case 2:
                    List<String> addresses = new ArrayList<>();
                    for (int i = 0; i < UserMsg.goodsBuyAddressInfo.size(); i++) {
                        addresses.add(UserMsg.goodsBuyAddressInfo.get(i).getDistrict());
                    }
                    UserMsg.goodsBuyAddress.addAll(addresses);
                    break;
                case 3:
                    setIp((String) msg.obj);
                    break;
                case 4:

            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getViews();
        setListeners();
        Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.default_avatar);
        avatar.setImageBitmap(ImgUtil.toRoundBitmap(mBitmap));
    }
    private void setIp(String ip) {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody body= new FormBody.Builder()
                .add("userId", UserMsg.userDTO.getUserId() + "")
                .add("ipAddress", ip)
                .build();
        Request request = new Request.Builder()
                .url(Constant.SETIP)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("ip","设置失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("ip", result);
            }
        });
    }
    private void setListeners() {
        regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), RegistActivity.class);
                startActivity(intent);
            }
        });
        exchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPassword) {
                    isPassword = false;
                    exchange.setText("密码登录");
                    passwordLogin.setVisibility(View.INVISIBLE);
                    codeLogin.setVisibility(View.VISIBLE);
                    forgetPassword.setVisibility(View.INVISIBLE);
                } else {
                    isPassword = true;
                    exchange.setText("验证码登录");
                    passwordLogin.setVisibility(View.VISIBLE);
                    codeLogin.setVisibility(View.INVISIBLE);
                    forgetPassword.setVisibility(View.VISIBLE);
                }
            }
        });
        getCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(phone.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "请填写手机号", Toast.LENGTH_SHORT).show();
                } else {
                    if (judgePhone(phone.getText().toString())) {
                        Toast.makeText(getApplicationContext(), "验证码已发送", Toast.LENGTH_LONG).show();
                        getCode();
                    } else {
                        Toast.makeText(getApplicationContext(), "手机号不正确", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //密码登录
                if (!isPassword) {
                    if (("".equals(phone.getText().toString())) && (!"".equals(code.getText().toString()))) {
                        Toast.makeText(getApplicationContext(), "手机号不能为空", Toast.LENGTH_SHORT).show();
                    }
                    if ((!"".equals(phone.getText().toString())) && ("".equals(code.getText().toString()))) {
                        Toast.makeText(getApplicationContext(), "验证码不能为空", Toast.LENGTH_SHORT).show();
                    }
                    if (("".equals(phone.getText().toString())) && ("".equals(code.getText().toString()))) {
                        Toast.makeText(getApplicationContext(), "手机号和验证码不能为空", Toast.LENGTH_SHORT).show();
                    }
                    if ((!"".equals(phone.getText().toString())) && (!"".equals(code.getText().toString()))) {
                        if (judgePhone(phone.getText().toString())) {
                            toLoginByCode();
                        } else {
                            Toast.makeText(getApplicationContext(), "手机号不正确", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                //验证码登录
                else {
                    if (("".equals(phone.getText().toString())) && (!"".equals(password.getText().toString()))) {
                        Toast.makeText(getApplicationContext(), "手机号不能为空", Toast.LENGTH_SHORT).show();
                    }
                    if ((!"".equals(phone.getText().toString())) && ("".equals(password.getText().toString()))) {
                        Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_SHORT).show();
                    }
                    if (("".equals(phone.getText().toString())) && ("".equals(password.getText().toString()))) {
                        Toast.makeText(getApplicationContext(), "手机号和密码不能为空", Toast.LENGTH_SHORT).show();
                    }
                    if ((!"".equals(phone.getText().toString())) && (!"".equals(password.getText().toString()))) {
                        if (judgePhone(phone.getText().toString())) {
                            toLoginByPassword();
                        } else {
                            Toast.makeText(getApplicationContext(), "手机号不正确", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });
        forgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
            }
        });
    }

    private boolean judgePhone(String phoneNum) {
        boolean mobileNO = PhoneUtil.isMobileNO(phoneNum);
        return mobileNO;
    }

    private void toLoginByPassword() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.LOGINPASSWORD + "phone=" + phone.getText().toString() + "&password=" + password.getText().toString())
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loginSuccess(result);
                    }
                });

            }
        });
    }

    private void loginSuccess(String result){

        Log.e("loginsuccess",result);
        Gson gson = new Gson();
        UserDTO userDTO = gson.fromJson(result,UserDTO.class);

        Log.e("login",userDTO + "");
        if (userDTO != null && userDTO.getUserId() != null) {
            Constant.isLogin = true;
            System.out.println("类:" + userDTO.toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                }
            });
            String ip = ChatUtil.getIPAddress(getApplicationContext());
            userDTO.setIpAddress(ip);
            UserMsg.userDTO = userDTO;
            ChatUtil.buildServer(getApplicationContext());
            Message message = new Message();//获取该用户的地址
            message.what = 1;
            handler.sendMessage(message);

            Message message1 = new Message();//设置该用户当前ip
            message1.what = 3;
            message1.obj = ip;
            handler.sendMessage(message1);

            ListenerManager listenerManager = new ListenerManager(LoginActivity.this);
            listenerManager.getInstance(LoginActivity.this).updata();

//                    setResult(101,intent);
            finish();
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void toLoginByCode() {

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.LOGINCODE + "phone=" + phone.getText().toString() + "&code=" + code.getText().toString())
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("login", "codelogin:" + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result != null) {
                            loginSuccess(result);
                        } else {
                            Toast.makeText(getApplicationContext(), "验证码过期", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }
        });
    }

    private void getCode() {
        Log.e("getcode", phone.getText().toString());
        FormBody body = new FormBody.Builder()
                .add("phone", phone.getText().toString())
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .post(body)
                .url(Constant.GETCODE)
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("login", result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    String isLogin = jsonObject.getString("data");
//                    Log.e("LoginData", isLogin);
////                    JSONObject object = new JSONObject(isLogin);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
            }
        });
    }
    private void getViews() {
        avatar = findViewById(R.id.login_avatar);
        passwordLogin = findViewById(R.id.login_bypassword);
        codeLogin = findViewById(R.id.login_bycode);
        phone = findViewById(R.id.login_phone);
        password = findViewById(R.id.login_password);
        code = findViewById(R.id.login_code);
        getCodeBtn = findViewById(R.id.login_getcode);
        loginBtn = findViewById(R.id.login);
        exchange = findViewById(R.id.login_exchange);
        regist = findViewById(R.id.regist);
        forgetPassword = findViewById(R.id.forget_password);
    }
    private void getAddress() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.GETADDRESS + UserMsg.userDTO.getUserId())
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("add", result);
                Gson gson = new Gson();

                Type type = new TypeToken<List<AddressInfoDTO>>(){}.getType();
                List<AddressInfoDTO> list = gson.fromJson(result,type);
                UserMsg.goodsBuyAddressInfo = list;
                Message message = new Message();
                message.what = 2;
                handler.sendMessage(message);

            }
        });
    }
}